package com.odds.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.NodeClassFilter;
import org.htmlparser.tags.LinkTag;
import org.htmlparser.tags.TableColumn;
import org.htmlparser.tags.TableRow;
import org.htmlparser.tags.TableTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.htmlparser.util.SimpleNodeIterator;

import com.odds.bean.ChangCiVo;
import com.odds.bean.OuzhiBaseVo;
import com.odds.bean.OuzhiSubVo;
import com.odds.bean.OuzhiVo;

public class ParserHtmlTable {
	final static String resourcePath = "E://JavaStudio//workspace//resource//";
	String separator = System.getProperty("file.separator");

	public static void main(String[] args) throws Exception {
		ParserHtmlTable p = new ParserHtmlTable();
		 String[] qiShus = {"100920","100919","100918","100917","100916"};
		 String[] qiShus3 = {"100915","100914","100913","100912","100911","100910","100909","100908","100907","100906","100905","100904","100903","100902","100901"};
		 String[] qiShus1 = {"100821","100820","100819","100818","100817","100816","100815","100814","100813","100812","100811","100810","100809","100808","100807","100806","100805","100804","100803","100802","100801"};
		 String[] qiShus4 ={"101007"};
		 p.downloadTableVs(qiShus4);
		 p.init( qiShus4);
		String file = "E:\\JavaStudio\\workspace\\resource\\201010\\101006\\101006-1墨尔本心VS墨尔本胜\\101006-1墨尔本心VS墨尔本胜_欧赔.html";
		String file2 = "E:\\JavaStudio\\workspace\\resource\\201010\\101006\\101006-29葡萄牙VS丹麦\\101006-29葡萄牙VS丹麦_欧赔.html";
		List<String> list = new ArrayList<String>();
		list.add(file);
		list.add(file2);
		p.doWithOuzhi(list);

	}

	/**
	 * 
	 *    1、是胆选的主要对象，在好多情况下可以只选一赔结果（就是DH型只选择3、HD型只选择0）；
          2、必要的时候可以进行复选（就是选择两个结果），以正选为主（就是DH型选择31、HD型选择10）；
          3、在少数情况下有出现反选结果的可能，要具体问题具体分析（就是DH型为0、HD型为3）。
          4、需要三包的情况比较少，主要出现在玩家投注和三个结果的包容率比较接近的时候。
          
          
          本人在利用赔率统计法进行分析方面做出了很多尝试，目的是在如何应用上向大家作些介绍。鉴于笔者能力有限，只想起到抛砖引玉的作用，但愿得到举一反三的效果。大家对自己感兴趣的研究对象应用此法，一定会有更多新的发现。   

附录：什么是DH型和HD型。

现有交易赔率（概率赔率不在此列）分为:ＤＨ、ＤＤ、ＳＨＤ、ＳＰＨＤ、ＮＰＨＤ、ＮＨＤ、ＨＤ、Ｐ型八种基本类型，具体的分型标准如下:
    DH型: 胜赔小于或等于2.10、平赔大于2.70、负赔大于3.70的赔率类型；
    DD型: 胜赔小于或等于2.10、平赔大于2.70、负赔小于或等于3.70的赔率类型；
    HD型：胜赔大于3.70、平赔大于2.70、负赔小于或等于2.10的赔率类型；
    SHD型：胜赔大于2.10、平赔大于2.70、负赔小于或等于3.70且胜赔小于负赔的赔率类型；
    SPHD型：胜赔大于2.10、平赔大于2.70、负赔小于3.70且胜赔小于或等于负赔其差值小于0.2的赔率类型；
    NPHD型：胜赔大于2.10、平赔大于2.70、负赔小于3.70且胜赔大于负赔其差值小于0.2的赔率类型；
    NHD型：胜赔大于2.10、平赔大于2.70、负赔小于3.70且胜赔大于负赔的赔率类型；
    P型：平赔小于或等于2.70的赔率类型.
    
    
这个赔率分型系统就被命名为DHPSN赔率分型系统.

	 * @param file
	 * @throws Exception
	 */
	private void doWithOuzhi(List<String> file) throws Exception {
		for (String f : file) {
			File fi = new File(f);
			if (!fi.exists()) {
				continue;
			}
			TableTag tableTag = getNodeTagById(f,"datatb");
			String newfN = fi.getName().substring(0, fi.getName().length()-5)+"_datatb.html";
			System.out.println(newfN);
			File nf = new File(fi.getParent()+separator+newfN);
			if (!nf.exists()) {
				writeStringToFile(fi.getParent()+separator+newfN, tableTag.toHtml());
			}
			TableRow[] tableRows = tableTag.getRows();
			System.out.println(tableRows.length);
			OuzhiVo ouzhiVo  = new OuzhiVo();
			for (int i = 0; i < 10; i++) {
				
				TableColumn[] tableColumns = tableRows[i].getColumns();
				for (int j = 0; j < tableColumns.length; j++) {
					String id = tableColumns[j].getAttribute("id");
					if (id==null) {
						continue;
					}
					if (id.endsWith("c")) {
						OuzhiSubVo ouzhiSubVo = new OuzhiSubVo();
					}
					if (id.endsWith("j")) {
						OuzhiSubVo ouzhiSubVo = new OuzhiSubVo();
						
					}
					System.out.println(tableColumns[j].getAttribute("id")+"-"+tableColumns[j].toPlainTextString());
				}
			}
		}
	}

	public String[] getQiShus() {
		String[] qishus = {};
		return qishus;
	}

	ReaderPageByUrl rb = new ReaderPageByUrl();

	public void downloadTableVs(String[] qiShus) throws Exception {
		String url = "http://trade.500wan.com/pages/info/bjdc/zc.php?msgmode=2&expect={0}";
		for (int i = 0; i < qiShus.length; i++) {
			String nurl = url.replace("{0}", qiShus[i]);
			File qf = getFileByQishu(qiShus[i]);
			System.out
					.println(qf.getParent() + separator + qiShus[i] + ".html");
			File f1 = new File(qf.getParent() + separator + qiShus[i] + ".html");
			if (!f1.exists()) {
				rb.createStaticPage(nurl, f1.getCanonicalPath());
			}
		}

	}

	public void init(String[] qiShus) throws Exception {
		List<File> filelist = new ArrayList<File>();
		for (int i = 0; i < qiShus.length; i++) {
			String date = "20" + qiShus[i].substring(0, 4);
			TableTag str = getTabTagHtml(resourcePath + date + separator
					+ qiShus[i] + ".html", qiShus[i]);
			List<ChangCiVo> list = parseTableTag(str, qiShus[i]);
			filelist.addAll(downLoadOddsHtml(list, qiShus[i]));
		}
		System.out.println(filelist.size());
//		for (File file : filelist) {
//			System.out.println(file);
//		}
	}

	public List<File> downLoadOddsHtml(List<ChangCiVo> list, String qiShu)
			throws Exception {
		String oldou = "http://odds.500wan.com/ouzhi_single.php?id={0}";
		String oddurl = "http://odds.500wan.com/fenxi/";
		/**
		 * 欧洲赔率
		 */
		String ouzhi = "ouzhi.php?id={0}";
		/**
		 * 亚洲赔率
		 */
		String yazhi = "yazhi.php?id={0}";
		/**
		 * 比分赔率
		 */
		String bifen = "bifen.php?id={0}";
		String[] types = { "欧赔", "亚盘", "比分" };
		String[] urls = { ouzhi, yazhi, bifen };
		List<ChangCiVo> k = list;
		List<File> filelist = new ArrayList<File>();
		File qiShuFile = getFileByQishu(qiShu);
		for (int j = 0; j < urls.length; j++) {
			for (int i = 0; i < k.size(); i++) {
				StringBuffer buffer = new StringBuffer();
				ChangCiVo cv = k.get(i);
				buffer.append(oddurl);
				buffer.append(urls[j].replace("{0}", cv.getUrlCode()));
				File file = new File(qiShuFile.getCanonicalFile() + separator
						+ cv.gerentefileName());
				if (!file.exists()) {
					file.mkdir();
				}
				File f1 = new File(file.getAbsolutePath() + separator
						+ cv.gerentefileName() + "_" + types[j] + ".html");
				if (!f1.exists()) {
					System.out.println("downing.." + buffer.toString()
							+ "  savefile:" + f1.getCanonicalPath());
					rb.createStaticPage(buffer.toString(),
							f1.getCanonicalPath());
				}
				filelist.add(f1);
			}
		}
		return filelist;
	}

	private File getFileByQishu(String qiShu) {
		String date = "20" + qiShu.substring(0, 4);
		File qiShuFile = new File(resourcePath + date + separator + qiShu);
		if (!qiShuFile.exists()) {
			qiShuFile.mkdirs();
		}
		return qiShuFile;
	}

	/**
	 * 读取对阵表表格
	 * 
	 * @param file
	 *            文件名
	 * @return 对阵表表格
	 * @throws Exception
	 */
	public TableTag getTabTagHtml(String file, String qishu) throws Exception {
		TableTag tableTag = getNodeTagById(file,"table_vs");
		String date = "20" + qishu.substring(0, 4);
		if (!new File(resourcePath + "201010" + separator + qishu
				+ "_table_vs.html").exists()) {
			this.writeStringToFile(resourcePath + date + separator
					+ qishu + "_table_vs.html", tableTag.toHtml());
		}
		return tableTag;
	}

	private TableTag getNodeTagById(String file,String id)
			throws ParserException, Exception {
		NodeList nodeList = initParser(file);

		TableTag tableStr = null;
		for (SimpleNodeIterator iterator = nodeList.elements(); iterator
				.hasMoreNodes();) {
			Node node = (Node) iterator.nextNode();
			if (node instanceof TableTag) {
				TableTag tableTag = (TableTag) node;
				if (id.equals(tableTag.getAttribute("id"))) {
					return tableTag;
				}
			}
		}
		return tableStr;
	}

	private NodeList initParser(String file) throws ParserException {
		String content = readTextFile(file, "GBK");
		Parser myParser = Parser.createParser(content, "GBK");

		NodeFilter tableFilter = new NodeClassFilter(TableTag.class);
		NodeList nodeList = myParser.parse(tableFilter);
		return nodeList;
	}

	/**
	 * @param tablehtml
	 * @throws Exception
	 */
	public List<ChangCiVo> parseTableTag(TableTag tabletag, String qishu)
			throws Exception {
		TableRow[] tableRows = tabletag.getRows();
		List<ChangCiVo> list = new ArrayList<ChangCiVo>();
		for (int i = 3; i < tableRows.length; i++) {
			ChangCiVo changCiVo = new ChangCiVo();
			changCiVo.setLianSai(tableRows[i].getAttribute("teamname"));
			TableColumn[] tableColumns = tableRows[i].getColumns();
			if (tableColumns.length == 1) {
				continue;
			}
			// 期数
			changCiVo.setId(qishu + "-" + tableColumns[0].toPlainTextString());
			changCiVo.setTeamA(tableColumns[4].toPlainTextString());
			changCiVo.setTeamB(tableColumns[6].toPlainTextString());
			changCiVo.setBiFen(tableColumns[7].getChild(0).getFirstChild()
					.toPlainTextString().trim());
			changCiVo.setRangQiu(tableColumns[5].toPlainTextString());
			// System.out.println(tableColumns[14].toHtml());
			changCiVo.setUrlCode(this.parseLinkParma(tableColumns[14]
					.getChild(0)));
			System.out.println(changCiVo);
			list.add(changCiVo);
		}
		return list;
	}

	public String parseLinkParma(Node urlNode) {
		String tarUrl = ((LinkTag) urlNode).getAttribute("href");
		String param = tarUrl.substring(tarUrl.indexOf("?") + 1);
		String[] params = param.split("&");
		String tmp = "";
		if (params.length > 1) {
			for (int i = 0; i < params.length; i++) {
				if (params[i].split("=")[0].equals("id")) {
					tmp = params[i].split("=")[1];
				}
			}
		}
		return tmp;
	}

	/**
	 * 读取一个文件到字符串里.
	 * 
	 * @param sFileName
	 *            文件名
	 * @param sEncode
	 *            String
	 * @return 文件内容
	 */
	public static String readTextFile(String sFileName, String sEncode) {
		StringBuffer sbStr = new StringBuffer();

		try {
			File ff = new File(sFileName);
			InputStreamReader read = new InputStreamReader(new FileInputStream(
					ff), sEncode);
			BufferedReader ins = new BufferedReader(read);

			String dataLine = "";
			while (null != (dataLine = ins.readLine())) {
				sbStr.append(dataLine);
				sbStr.append("\r\n");
			}

			ins.close();
		} catch (Exception e) {
		}

		return sbStr.toString();
	}

	/**
	 * 写入操作
	 * 
	 * @param filePath
	 *            静态页面路径
	 * @param fileStr
	 *            网页内容
	 * @throws Exception
	 */
	public void writeStringToFile(String filePath, String fileStr)
			throws Exception {
		File file = new File(filePath);
		FileOutputStream fileout = new FileOutputStream(file);
		fileout.write(fileStr.getBytes("gbk"));
		fileout.close();
	}
}
